package cn.centec.core.util;

import cn.centec.core.exception.ErrorRuntimeException;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * Http 客户端请求工具
 *
 * @author yxl
 *
 * @version 2.0
 *
 * @since 2016年8月11日
 */
public final class HttpUtil {

	/**
	 * POST请求
	 * 
	 * @param url
	 * @param params
	 * @return
	 * @throws
	 */
	public static String doPost(String url, Map<String, String> params){
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		// 创建Http Post请求
		HttpPost httpPost = new HttpPost(url);
		try {
			// 创建Httpclient对象
			httpClient = HttpClients.createDefault();
			// 添加请求参数
			setParams(httpPost, params);
			// 执行http请求
			response = httpClient.execute(httpPost);
			// 返回结果
			return getResponse(response,url);
		}catch (IOException e) {
			throw new ErrorRuntimeException("请求远程服务失败：" + url, e);
		}finally{
			if (httpClient != null) {
				try {
					httpClient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	

	
	/**
	 * 设置POST请求参数
	 * 
	 * @param httpPost
	 * @param params
	 * @throws UnsupportedEncodingException
	 */
	private static void setParams(HttpPost httpPost, Map<String, String> params){
		// 参数的键值对
		List<NameValuePair> paramList = new ArrayList<>();
		String value;
		for (Entry<String, String> entry : params.entrySet()) {
			value = entry.getValue();
			paramList.add(new BasicNameValuePair(entry.getKey(), value.trim()));
		}
		// 模拟表单
		UrlEncodedFormEntity entity = null;
		try {
			entity = new UrlEncodedFormEntity(paramList, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		httpPost.setEntity(entity);
	}

	/**
	 * 获取请求结果
	 * 
	 * 场景：UTF-8文本
	 * 
	 * @param response
	 * 
	 * @return
	 * 
	 * @throws IOException
	 */
	private static String getResponse(CloseableHttpResponse response, String url)throws IOException {
		// 状态码
		int statusCode = response.getStatusLine().getStatusCode();
		if (statusCode == 200) {
			return EntityUtils.toString(response.getEntity(), "UTF-8");
		}else{
			throw new ErrorRuntimeException("请求远程服务失败：url = " + url +", code = " + statusCode);
		}
	}


}
